package com.neuedu.wemall.member.controller;

import cn.hutool.core.lang.Validator;
import cn.hutool.core.util.StrUtil;
import com.neuedu.wemall.common.util.RedisUtils;
import com.neuedu.wemall.common.util.SignUtils;
import jakarta.servlet.http.HttpServletRequest;
import lombok.Data;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RestController;

@RestController
@Data
public abstract class BaseController {
    @Autowired
    private RedisUtils redis;
    @Autowired
    private HttpServletRequest request;

    /**
     * 根据token值获取会员用户ID
     *
     * @return
     */
    protected int getMemberUserID() {
        String token = getRequestToken();
        if (StrUtil.isEmpty(token)) {
            throw new IllegalArgumentException("令牌为空");
        }
        String tokenKey =getTokenKey(token);
        String signStr = redis.get(tokenKey).toString();
        //会员用户ID
        int userId = Integer.parseInt(SignUtils.getId(signStr));
        return userId;
    }

    /**
     * 获取令牌key(会员用户中心业务请求)
     *
     * @return
     */
    protected String getTokenKey() {
        String token = getRequestToken();
        return getTokenKey(token);
    }

    /**
     * 获取令牌key(登录成功后)
     *
     * @param token 令牌
     * @return
     */
    protected String getTokenKey(String token) {
        if (StrUtil.isEmpty(token)) {
            throw new IllegalArgumentException("令牌为空");
        }
        return SignUtils.getTokenKey(token);
    }

    /**
     * 获取登录邮箱key
     *
     * @param email
     * @return
     */
    protected String getLoginKey(String email) {
        if (StrUtil.isEmpty(email)) {
            throw new IllegalArgumentException("邮箱为空");
        }
        if (!Validator.isEmail(email, false)) {
            throw new IllegalArgumentException("邮箱格式错误");
        }
        return SignUtils.getLoginKey(email);
    }

    /**
     * 获取客户端传递的令牌
     * 需要进行如下检查
     * 1.客户端是否传递token(令牌)
     * 2.令牌是否过期
     * 3.令牌是否合法
     *
     * @return
     */
    protected String getRequestToken() {
        String clientToken = request.getParameter("token");
        if (clientToken == null) {
            clientToken = request.getHeader("wemall-token");
        }
        if (StrUtil.isEmpty(clientToken)) {
            throw new IllegalArgumentException("令牌为空");
        }
        String tokenKey = getTokenKey(clientToken);
        if (!redis.hasKey(tokenKey)) {
            throw new IllegalArgumentException("令牌已过期或无效的令牌");
        }
        ;
        //判断是否合法token,即token是不是会员本人的token,是否盗用其他会员用户token或token有没有被篡改
        String signStr = redis.get(tokenKey).toString();
        if (!SignUtils.validateToken(clientToken, signStr, request)) {
            throw new IllegalArgumentException("非法的令牌,请重新登录获取令牌");
        }
        return clientToken;
    }

}
